﻿using ShiQuan.HttpServer;
using ShiQuan.TcpServer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinServer
{
    public class FrmMain : Form
    {
        private GroupBox groupBox1;
        private Button btnConnect;
        private TextBox txtPort;
        private Label label2;
        private StatusStrip sysStatusBar;
        private TabControl tabControl1;
        private TabPage tabPage1;
        private RichTextBox richTextBox1;
        private ToolStripStatusLabel sysStatusLabel;

        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.btnConnect = new System.Windows.Forms.Button();
            this.txtPort = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.sysStatusBar = new System.Windows.Forms.StatusStrip();
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.tabPage1 = new System.Windows.Forms.TabPage();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.sysStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.groupBox1.SuspendLayout();
            this.sysStatusBar.SuspendLayout();
            this.tabControl1.SuspendLayout();
            this.tabPage1.SuspendLayout();
            this.SuspendLayout();
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.btnConnect);
            this.groupBox1.Controls.Add(this.txtPort);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top;
            this.groupBox1.Location = new System.Drawing.Point(0, 0);
            this.groupBox1.Margin = new System.Windows.Forms.Padding(5);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(384, 55);
            this.groupBox1.TabIndex = 2;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "网络设置";
            // 
            // btnConnect
            // 
            this.btnConnect.Location = new System.Drawing.Point(201, 20);
            this.btnConnect.Name = "btnConnect";
            this.btnConnect.Size = new System.Drawing.Size(75, 23);
            this.btnConnect.TabIndex = 5;
            this.btnConnect.Text = "开始";
            this.btnConnect.UseVisualStyleBackColor = true;
            // 
            // txtPort
            // 
            this.txtPort.Location = new System.Drawing.Point(95, 22);
            this.txtPort.Name = "txtPort";
            this.txtPort.Size = new System.Drawing.Size(100, 21);
            this.txtPort.TabIndex = 3;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 25);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(77, 12);
            this.label2.TabIndex = 1;
            this.label2.Text = "本地主机端口";
            // 
            // sysStatusBar
            // 
            this.sysStatusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.sysStatusLabel});
            this.sysStatusBar.Location = new System.Drawing.Point(0, 239);
            this.sysStatusBar.Name = "sysStatusBar";
            this.sysStatusBar.Size = new System.Drawing.Size(384, 22);
            this.sysStatusBar.SizingGrip = false;
            this.sysStatusBar.TabIndex = 12;
            this.sysStatusBar.Text = "statusStrip1";
            // 
            // tabControl1
            // 
            this.tabControl1.Controls.Add(this.tabPage1);
            this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControl1.Location = new System.Drawing.Point(0, 55);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(384, 184);
            this.tabControl1.TabIndex = 13;
            // 
            // tabPage1
            // 
            this.tabPage1.Controls.Add(this.richTextBox1);
            this.tabPage1.Location = new System.Drawing.Point(4, 22);
            this.tabPage1.Name = "tabPage1";
            this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage1.Size = new System.Drawing.Size(376, 158);
            this.tabPage1.TabIndex = 0;
            this.tabPage1.Text = "数据接收";
            this.tabPage1.UseVisualStyleBackColor = true;
            // 
            // richTextBox1
            // 
            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox1.Location = new System.Drawing.Point(3, 3);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(370, 152);
            this.richTextBox1.TabIndex = 2;
            this.richTextBox1.Text = "";
            // 
            // sysStatusLabel
            // 
            this.sysStatusLabel.Name = "sysStatusLabel";
            this.sysStatusLabel.Size = new System.Drawing.Size(338, 17);
            this.sysStatusLabel.Spring = true;
            this.sysStatusLabel.Text = "toolStripStatusLabel1";
            this.sysStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // FrmMain
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(384, 261);
            this.Controls.Add(this.tabControl1);
            this.Controls.Add(this.sysStatusBar);
            this.Controls.Add(this.groupBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Name = "FrmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Form1";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.sysStatusBar.ResumeLayout(false);
            this.sysStatusBar.PerformLayout();
            this.tabControl1.ResumeLayout(false);
            this.tabPage1.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        public FrmMain()
        {
            InitializeComponent();

            this.Load += FrmMain_Load;
        }

        private AsyncTcpServer server;
        private SocketServer tcpServer;
        private System.Timers.Timer sysTimer = new System.Timers.Timer();
        private System.Threading.Thread sysThread;

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.btnConnect.Click += BtnConnect_Click;
        }

        private void BtnConnect_Click(object sender, EventArgs e)
        {
            if (this.btnConnect.Text == "开始")
            {
                Cursor = Cursors.WaitCursor;
                try
                {
                    int port = 80;
                    int.TryParse(this.txtPort.Text, out port);
                    if (port <= 0)
                        port = 80;

                    server = new AsyncTcpServer(port);
                    server.Encoding = Encoding.UTF8;
                    server.ClientConnected += Server_ClientConnected;
                    server.ClientDisconnected += Server_ClientDisconnected;
                    server.ClientReceived += Server_ClientReceived;
                    server.PlaintextReceived += Server_PlaintextReceived;
                    server.Start();

                    //this.tcpServer = new TcpServer(port);
                    //this.tcpServer.Encoding = Encoding.UTF8;
                    //this.tcpServer.ClientConnected += TcpServer_ClientConnected;
                    //this.tcpServer.ClientDisconnected += TcpServer_ClientDisconnected;
                    //this.tcpServer.ClientReceived += TcpServer_ClientReceived;
                    //this.tcpServer.PlaintextReceived += TcpServer_PlaintextReceived;
                    //this.tcpServer.Start();

                    //Console.WriteLine("TCP server has been started.");
                    //Console.WriteLine("Type something to send to client...");
                    //while (true)
                    //{
                    //    string text = Console.ReadLine();
                    //    server.SendAll(text);
                    //}
                    this.txtPort.Enabled = false;
                    this.richTextBox1.Text = "";
                    this.btnConnect.Text = "关闭";
                    this.sysStatusLabel.Text = "服务器打开！";
                }
                catch (Exception ex)
                {
                    this.Error(ex);
                }
                finally
                {
                    Cursor = Cursors.Default;

                }
            }
            else
            {
                Cursor = Cursors.WaitCursor;
                try
                {
                    if(this.server != null)
                        this.server.Dispose();
                    if (this.tcpServer != null)
                        this.tcpServer.Dispose();

                    this.txtPort.Enabled = true;
                    this.btnConnect.Text = "开始";
                    this.sysStatusLabel.Text = "服务器关闭！";
                }
                catch (Exception ex)
                {
                    this.Error(ex);
                }
                finally
                {
                    Cursor = Cursors.Default;

                }
            }
        }

        private void TcpServer_ClientConnected(object sender, SocketConnectedEventArgs e)
        {
            this.AppendText(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.Socket.RemoteEndPoint.ToString() + " connected!\n");
        }

        private void TcpServer_PlaintextReceived(object sender, SocketReceivedEventArgs<string> e)
        {
            try
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.Socket.RemoteEndPoint.ToString());
                msg.AppendLine(e.Datagram);

                System.IO.File.WriteAllText(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".db", msg.ToString(), System.Text.Encoding.UTF8);

                //this.richTextBox1.AppendText(msg.ToString());
                //this.richTextBox1.ScrollToCaret();
                this.AppendText(msg.ToString());

                var result = System.Text.Encoding.UTF8.GetBytes("接收成功！");
                e.Socket.Send(result);
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
        }

        private void TcpServer_ClientReceived(object sender, SocketReceivedEventArgs<byte[]> e)
        {
            
        }

        private void TcpServer_ClientDisconnected(object sender, SocketDisconnectedEventArgs e)
        {
            this.AppendText(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.Socket.RemoteEndPoint.ToString() + " disconnected!\n");
        }

        private void Server_ClientConnected(object sender, TcpClientConnectedEventArgs e)
        {
            this.AppendText(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.TcpClient.Client.RemoteEndPoint.ToString() + " connected!\n");
        }

        private void Server_PlaintextReceived(object sender, TcpClientReceivedEventArgs<string> e)
        {
            try
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.TcpClient.Client.RemoteEndPoint.ToString());
                msg.AppendLine(e.Datagram);

                System.IO.File.WriteAllText(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".db", msg.ToString(), System.Text.Encoding.UTF8);
                
                //this.richTextBox1.AppendText(msg.ToString());
                //this.richTextBox1.ScrollToCaret();
                this.AppendText(msg.ToString());

                //this.server.Send(e.TcpClient, "接收成功！");
                var result = System.Text.Encoding.UTF8.GetBytes("接收成功");
                e.TcpClient.GetStream().Write(result, 0, result.Length);
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
        }

        private void Server_ClientReceived(object sender, TcpClientReceivedEventArgs<byte[]> e)
        {
            
        }

        private void Server_ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e)
        {
            this.AppendText(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.TcpClient.Client.RemoteEndPoint.ToString() + " disconnected!\n");
        }

        private delegate void OnAppendText(string msg);

        private void AppendText(string msg)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                OnAppendText appendText = new OnAppendText(this.AppendText);
                //appendText.Invoke(msg);
                this.Invoke(appendText, new object[] { msg });
            }
            else
            {
                this.richTextBox1.AppendText(msg);
                this.richTextBox1.ScrollToCaret();
            }
        }
        private void Error(Exception ex)
        {
            System.IO.File.AppendAllText(Application.StartupPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".db", ex.ToString() + "\n");
            //MessageBox.Show("异常：" + ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.AppendText("异常：" + ex.Message);
        }
    }
}
